<!-- 数据上传，lbw -->
<script setup lang="ts" name="DataUpload">
import {onActivated, reactive, ref, watch} from 'vue'
import {onMounted} from 'vue'
import { ElMessage, ElMessageBox, FormRules} from 'element-plus'

import {
  HeaderData
} from '@/components/dTable/dTable'
import {
  OperButton,
  SearchFromItem,
  SearchButton,
  SearchFromJustify
} from '@/components/dTable/dHeader'
import {
  PageConfig,
  defaultPage,
  defaultPageSize,
  defaultPageSizes,
  defaultLayout
} from '@/components/dTable/dFooter'
import {getYearMonthDayStr} from '@/util/common'

import {getUploadList, GetUploadList, downloadData, uploadData} from '@/api/dataManagement/dataUpload'
import pageContainer from '@/components/pageContainer.vue'
import dTablePromote from '@/components/dTable/dTablePromote.vue'
import {SeleteData} from '@/api/config'

// 字典
const uploadStatuList = ref<Array<SeleteData>>([{label:'未上传', value:0}, {label:'已上传', value:1}])


//数据
const tableData = ref<Array<GetUploadList >>([])

//显示加载状态
const showLoading = ref(false)

//表格数据
const tableHeaderData = ref<Array<HeaderData>>([
  {
    prop: 'phyDate',
    label: '体检日期',
    columnType: 'text',
    align: 'left',
    'min-width': '109'
  },
  {
    prop: 'checkupNo',
    label: '体检号',
    columnType: 'text',
    align: 'left',
    'min-width': '102'
  },
  {
    prop: 'personName',
    label: '姓名',
    columnType: 'text',
    align: 'left',
    'min-width': '93'
  },
  {
    prop: 'idNo',
    label: '身份证号',
    columnType: 'text',
    align: 'left',
    'min-width': '103'
  },
  {
    prop: 'gender',
    label: '性别',
    columnType: 'text',
    align: 'left',
    'min-width': '93'
  },
  {
    prop: 'age',
    label: '年龄',
    columnType: 'text',
    align: 'left',
    'min-width': '93'
  },
  {
    prop: 'uploadTime',
    label: '上传时间',
    columnType: 'text',
    align: 'left',
    'min-width': '110'
  },
  {
    prop: 'uploadName',
    label: '上传人',
    columnType: 'text',
    align: 'left',
    'min-width': '97'
  }


])

//搜索项
const searchFromItems = ref<Array<SearchFromItem>>([

  {
    label: '体检日期',
    placeholder: ['开始时间', '结束时间'],
    type: 'antdRange',
    prop: 'phyDate',
    showTime: false,
    changeSubmit: false,
    notClearable: true,
    dateFormat: 'YYYY-MM-DD',
    style: {width: '310px'}
  },
  {
    label: '上传状态',
    placeholder: '请选择上传状态',
    type: 'selete',
    prop: 'uploadStatus',
    notClearable:true,
    seleteData: uploadStatuList.value
  }
])
//表头
const operButtons = ref<Array<OperButton>>([
  {
    label: '上传',
    type: 'noraml',
    iconConfig: {icon: 'common-uploads', type: 'custom'},
    code: 'add',
    disabled:false
  }
])
const searchFromData = reactive<GetUploadList>({uploadStatus: 0, phyDate:[getYearMonthDayStr(Date.now()), getYearMonthDayStr(Date.now())] })
watch(
  () => searchFromData,
  (showDrawer) => {
    if (searchFromData.uploadStatus ? true : false) {
      operButtons.value = [{
        label: '上传',
        type: 'noraml',
        iconConfig: {icon: 'common-uploads', type: 'custom'},
        code: 'add',
        disabled:true
      }]
    } else {
      operButtons.value = [{
        label: '上传',
        type: 'noraml',
        iconConfig: {icon: 'common-uploads', type: 'custom'},
        code: 'add',
        disabled:false
      }]
    }

  }, {deep:true}
)

const searchFromRules = reactive<FormRules>({
  id: [
    {
      required: false,
      message: '长度应不超过20个字符',
      max: 20,
      trigger: ['change', 'blur']
    }
  ]

})

//表单靠左还是靠右
const searchFromJustify = ref<SearchFromJustify>('flexStart')

//搜索按钮配置
const searchButtons = ref<Array<SearchButton>>([
  {type: 'search'},
  {type: 'clear'}
])

//分页配置
const pageConfig = ref<PageConfig>({
  currentPage: defaultPage,
  pageSize: defaultPageSize,
  pageSizes: defaultPageSizes,
  total: 0,
  disabled: false,
  layout: defaultLayout
})

//后端数据拼接字段
const setTableData = (data: Array<GetUploadList>) => {
  const dataArr: Array<GetUploadList> = []
  data.forEach((item) => {
    dataArr.push({...item})
  })
  tableData.value = dataArr
}
// 获取搜索数据
const getSearchParams = (searchFromData:GetUploadList):GetUploadList => {

  const {uploadStatus, phyDate} = searchFromData
  const pararms:GetUploadList = {uploadStatus}
  if (phyDate) {
    pararms.startPhyDate = phyDate[0] + ' 00:00:00'
    pararms.endPhyDate = phyDate[1] + ' 23:59:59'
  }

  return pararms
}

//搜索数据
const searchData = (resetPage?: boolean) => {
  showLoading.value = true
  if (resetPage) pageConfig.value.currentPage = 1
  const params = getSearchParams(searchFromData)

  getUploadList({
    ...params,
    page: pageConfig.value.currentPage,
    limit: pageConfig.value.pageSize
  })
    .then((res) => {
      const {records} = res.data.data
      pageConfig.value.total =
        res.data.data.total === null ? 0 : res.data.data.total
      setTableData(records)
    })
    .catch((error) => {
      console.warn(error)
    })
    .finally(() => {
      showLoading.value = false
    })
}
// '<strong>proxy is <i>HTML</i> string</strong>',
const lastBoxData = ref<string>('')
// 第二个弹窗
const lastBox = () => {
  ElMessageBox.confirm(
    '检验数据同步lis失败，失败原因如下：' + lastBoxData.value,
    '提示',
    {
      confirmButtonText: '关闭',
      showCancelButton:false, dangerouslyUseHTMLString: true,
      type: 'warning'
    }
  ).then(res => {
    searchData()
  }).catch(res => {
    ElMessage.error('上传失败')
  })
}
// 获取搜索数据
const onDownloadData = () => {
  lastBoxData.value = ''
  uploadData().then(res => {
    if (res.data && res.data.msg) {
      if (res.data && res.data.data) {
        res.data.data.forEach(key => {
          if (key)  lastBoxData.value += '<div>' + key + '</div>'
        })
      }
      ElMessageBox.confirm(
        res.data.msg ? res.data.msg : '',
        '提示',
        {
          confirmButtonText: '关闭',
          showCancelButton:false,
          type: 'warning'
        }
      ).then(res => {
        if (lastBoxData.value) {
          lastBox()
        } else {
          searchData()
        }
      }).catch(res => {
        if (lastBoxData.value) {
          lastBox()
        } else {
          ElMessage.error('上传失败')
        }

      })

    }

  })
}
//操作按钮事件
const onOperation = (code: string) => {
  if (code === 'add') {
    if (tableData.value && tableData.value.length) {
      onDownloadData()
    } else {
      ElMessage.error('没有上传数据')

    }
  }
}





//搜索事件
const onSubmit = () => {
  searchData(true)
}

//清除搜索栏数据
const clearForm = () => {
  searchData(true)
}

//清空搜索表单事件
const onFormClear = () => {
  searchFromData.phyDate = [getYearMonthDayStr(Date.now()), getYearMonthDayStr(Date.now())]
  searchFromData.uploadStatus = 0

  clearForm()
}
//分页尺寸改变事件
const onSizeChange = () => {
  searchData(true)
}

//当前页改变事件
const onCurrentChange = () => {
  searchData()
}

onActivated(() => {
  searchData()
})
onMounted(() => {
  // getDict()
})
</script>

<template>
  <page-container>
    <d-table-promote
      :oper-buttons="operButtons"
      :search-form-items="searchFromItems"
      :search-buttons="searchButtons"
      :search-form-data="searchFromData"
      :search-rules="searchFromRules"
      :table-data="tableData"
      :table-header-data="tableHeaderData"
      :page-config="pageConfig"
      :search-from-justify="searchFromJustify"
      :show-loading="showLoading"
      :stripe="true"
      @form-submit="onSubmit"
      @form-clear="onFormClear"
      @operation="onOperation"

      @size-change="onSizeChange"
      @current-change="onCurrentChange"
    />
  </page-container>
</template>

<style scoped></style>
<style>
.report-type .el-form-item__content{
  margin-left: 0 !important;
  width: unset;
}
.report-type .report-select-type{
  width: 106px;
  margin-right: 8px;
}
.report-type .ant-picker{
  width: 286px;
}
.report-type .report-select{
  width: 286px;
}
</style>

